import { getSetting, openSetting, chooseAddress, showModal, showToast, requestPayment } from "../../utils/asyncWx.js";
import regeneratorRuntime from '../../lib/runtime/runtime';
import { request } from '../../request/index.js'
/**
 * 微信支付：
 *    只有企业级账号才可以调用微信支付功能
 * 
 * 支付：
 *    1. 从缓存里面 获取token
 *    2. 判断token是否存在
 *    3. 如果不存在 跳转到授权页面 去获取token
 *    4. 如果存在 就正常执行，创建订单
 */
Page({

  /**
   * 页面的初始数据
   */
  data: {
    address: {},
    cart: [],
    // 选中商品总价
    totalPrice: 0,
    // 选中商品总个数
    totalNum: 0
  },

  onShow() {
    let address = wx.getStorageSync("address");
    let cart = wx.getStorageSync("cart") || [];
    // 对 cart 过滤
    cart = cart.filter(v => v.checked);

    let totalPrice = 0;
    let totalNum = 0;
    cart.forEach((v, i) => {
      totalNum += v.num;
      totalPrice += v.goods_price * v.num;
    });
    this.setData({
      address,
      cart,
      totalNum,
      totalPrice
    });
  },
  /**
   * 点击支付
   */
  async handlePay() {
    try {
      let token = wx.getStorageSync("token");
      if (!token) {
        // token 不存在 跳转页面
        wx.navigateTo({
          url: '/pages/auth/index'
        });
        return;
      }
      // 创建订单
      // 请求头
      // let header = { Authorization: token };
      // 订单总价格 
      let order_price = this.data.totalPrice;
      // 收货地址
      let consignee_addr = this.data.address.all;
      // 商品数组
      let goods = [];
      let cart = this.data.cart;
      cart.forEach(v => goods.push({
        goods_id: v.goods_id,
        goods_number: v.num,
        goods_price: v.goods_price
      }));
      let orderNumParms = { order_price, consignee_addr, goods }
      //1 创建订单
      let { order_number } = await request({ url: '/my/orders/create', method: 'post', data: orderNumParms });

      // 2预支付
      let { pay } = await request({ url: '/my/orders/req_unifiedorder', method: 'post', data: { order_number } });
      // 3发起微信支付
      // let res = await requestPayment(pay);

      // 4查看订单状态
      let res2 = await request({ url: '/my/orders/chkOrder', method: 'post', data: { order_number } });
      
      // 把支付过的商品从购物车里面清楚
      let newCart = wx.getStorageSync("cart");
      newCart=newCart.filter(v=>!v.checked);
      wx.setStorageSync("cart", newCart);
      // 跳转到订单页面
      wx.navigateTo({
        url: '/pages/order/index'
      });
      await showToast({title:'支付成功'});
    } catch (error) {
      await showToast({title:'支付失败'});
      console.log(error);

    }



  }
})